package server

import (
	"context"
	"fmt"
	"self/common/initiailze"
	"self/common/models"
	"self/common/proto/user"
	"time"
)

func Registers(in *user.RegisterReq) (*user.RegisterResp, error) {
	users := &models.User{}
	err := initiailze.DB.Where("username=?", in.Username).Find(&users).Error
	if err != nil {
		fmt.Println("查询失败")
		return nil, err
	}
	if users.ID != 0 {
		fmt.Println("用户名已注册")
		return nil, err
	}
	users = &models.User{
		Username: in.Username,
		Password: in.Password,
	}
	err = initiailze.DB.Create(&users).Error
	if err != nil {
		fmt.Println("注册失败")
		return nil, err
	}
	return &user.RegisterResp{Greet: "注册成功"}, nil
}
func UserList(in *user.UserListReq) (*user.UserListResp, error) {
	var users []*models.User
	err := initiailze.DB.Find(&users).Error
	if err != nil {
		fmt.Println("查询失败")
		return nil, err
	}
	var list []*user.UserList
	for _, m := range users {
		list = append(list, &user.UserList{
			Id:       int64(m.ID),
			Username: m.Username,
			Password: m.Password,
		})
	}
	initiailze.Rdb.Set(context.Background(), "userList", list, time.Hour*24)
	return &user.UserListResp{List: list}, nil
}
